package com.xiaoshuidi.cloud.module.report.xxljob;

import com.xiaoshuidi.cloud.framework.tenant.core.aop.TenantIgnore;
import com.xiaoshuidi.cloud.framework.tenant.core.job.TenantJob;
import com.xiaoshuidi.cloud.module.report.dal.DO.report.ReportLedgerInfoDO;
import com.xiaoshuidi.cloud.module.report.dal.mapper.ContractRentorderMapper;
import com.xiaoshuidi.cloud.module.report.dal.mapper.report.ReportLedgerInfoMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;

/**
 *
 * 处理台账已交押金和租金交至日期字段job每日23点跑
 */
@Component
@Slf4j
public class ReportLedgerDepositHandleJob {


    @Resource
    private ReportLedgerInfoMapper reportLedgerInfoMapper;
    @Resource
    private ContractRentorderMapper contractRentorderMapper;

    @XxlJob("reportLedgerDepositHandleJob")
    @TenantIgnore
    public void execute() {
        //分500 一批次处理
        int pageNo = 0;
        int pageSize = 500;
        List<ReportLedgerInfoDO> list = Collections.emptyList();
        do {
            int from = pageNo*pageSize;
            list = reportLedgerInfoMapper.selectAllLedgerByPage(from,pageSize);
            handleLedgerList(list);
            pageNo++;
        }while (list.size()==500);
    }

    private void handleLedgerList(List<ReportLedgerInfoDO> list){
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        for (ReportLedgerInfoDO infoDO : list) {
            BigDecimal totalDeposit = contractRentorderMapper.sumPayedTotalDepositByContractId(infoDO.getContractId());
            infoDO.setDeposit(totalDeposit);
            LocalDate rentDeliveryDate = contractRentorderMapper.selectRecentPayedEndTime(infoDO.getContractId());
            infoDO.setRentDeliveryDate(rentDeliveryDate);
        }
        reportLedgerInfoMapper.updateBatch(list,list.size());
        //将续租和换租的台账上份合同如果已退租 不在退租台账展示
        List<Long> longs = reportLedgerInfoMapper.selectContractIdByRenewalAndExchange();
        reportLedgerInfoMapper.updateRentingOutForRenewalAndExchange(longs);
    }
}
